package cn.tedu.csmall.product.repo.impl;


import cn.tedu.csmall.product.pojo.vo.AlbumListItemVo;
import cn.tedu.csmall.product.pojo.vo.AlbumStandardVo;
import cn.tedu.csmall.product.repo.IAlbumRedisRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Repository
public class AlbumRedisRepositoryImpl implements IAlbumRedisRepository {

    @Autowired
    private RedisTemplate<String, Serializable> redisTemplate;

    @Override
    public void save(AlbumStandardVo albumStandardVO) {
        String key = "album:item:" + albumStandardVO.getId();
        log.debug("即将向Redis中写入数据，Key={}，Value={}", key, albumStandardVO);
        redisTemplate.opsForValue().set(key, albumStandardVO);
    }

    @Override
    public void save(List<AlbumListItemVo> albumList) {
        String key = "album:list";
        ListOperations<String, Serializable> opsForList = redisTemplate.opsForList();
        for (AlbumListItemVo albumListItemVO : albumList) {
            log.debug("即将向Redis中写入列表项数据，Key={}，列表项={}", key, albumListItemVO);
            opsForList.rightPush(key, albumListItemVO);
        }
    }

    @Override
    public Boolean delete(Long id) {
        String key = "album:item:" + id;
        log.debug("即将删除Redis中的数据，Key={}", key);
        return redisTemplate.delete(key);
    }

    @Override
    public Boolean deleteList() {
        String key = "album:list";
        log.debug("即将删除Redis中的列表数据，Key={}", key);
        return redisTemplate.delete(key);
    }

    @Override
    public void deleteAllItem() {
        String key = "album:item:";
        redisTemplate.delete(key+"*");
    }

    @Override
    public AlbumStandardVo get(Long id) {
        String key = "album:item:" + id;
        log.debug("即将向Redis中取出数据，Key={}", key);
        Serializable serializable = redisTemplate.opsForValue().get(key);
        AlbumStandardVo albumStandardVO = null;
        if (serializable != null) {
            albumStandardVO = (AlbumStandardVo) serializable;
        }
        return albumStandardVO;
    }

    @Override
    public List<AlbumListItemVo> list() {
        long start = 0;
        long end = -1;
        return list(start, end);
    }

    @Override
    public List<AlbumListItemVo> list(long start, long end) {
        String key = "album:list";
        List<Serializable> serializableList = redisTemplate.opsForList().range(key, start, end);
        List<AlbumListItemVo> albumList = new ArrayList<>();
        for (Serializable serializable : serializableList) {
            albumList.add((AlbumListItemVo) serializable);
        }
        return albumList;
    }

}
